package com.example.demo.config;

import com.example.demo.Mapper.ChatMemoryMapper;
import com.example.demo.entity.ChatMemory;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import org.springframework.stereotype.Repository;
import java.util.List;
import static dev.langchain4j.data.message.ChatMessageDeserializer.messagesFromJson;
import static dev.langchain4j.data.message.ChatMessageSerializer.messagesToJson;

@Repository
public class PostgresChatMemoryStore implements ChatMemoryStore {

    private final ChatMemoryMapper chatMemoryMapper;

    public PostgresChatMemoryStore(ChatMemoryMapper chatMemoryMapper) {
        this.chatMemoryMapper = chatMemoryMapper;
    }

    @Override
    public List<ChatMessage> getMessages(Object memoryId) {
        ChatMemory chatMemory = chatMemoryMapper.selectById((String) memoryId);
        return chatMemory != null ? messagesFromJson(chatMemory.getMessages()) : List.of();
    }

    @Override
    public void updateMessages(Object memoryId, List<ChatMessage> messages) {
        System.out.println("目前有"+messages.size()+"条信息");
        // 确保 messages 只保留最近的 10 条
        if (messages.size() > 10) {
            messages = messages.subList(messages.size() - 10, messages.size());

        }
        String json = messagesToJson(messages);

        // 先查询数据库中是否已有该 memoryId
        ChatMemory existingMemory = chatMemoryMapper.selectById((String) memoryId);

        if (existingMemory != null) {
            // 更新已有的记录
            existingMemory.setMessages(json);
            chatMemoryMapper.updateById(existingMemory);
        } else {
            // 插入新记录
            ChatMemory chatMemory = new ChatMemory();
            chatMemory.setMemoryId((String) memoryId);
            chatMemory.setMessages(json);
            chatMemoryMapper.insert(chatMemory);
        }
    }


    @Override
    public void deleteMessages(Object memoryId) {
        chatMemoryMapper.deleteById((Long) memoryId);
    }
}

